<?php

namespace app\admin\controller;

use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use think\facade\Config;

class Module extends Common
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 模型列表
     * @author admin
     * @date 2019-08-08
     */
    public function index()
    {
        if (Request::isPost()) {
            $pageSize = input('limit') ? input('limit') : config('pageSize');

            $sort_by = input('sort_by') ? input('sort_by') : 'sort';
            $sort_order = input('sort_order') ? input('sort_order') : 'asc';
            $list = db::name('module')->order($sort_by . ' ' . $sort_order)
                ->paginate($pageSize)
                ->toArray();
            return ['code' => 0, 'msg' => '获取成功!', 'data' => $list['data'], 'count' => $list['total'], 'rel' => 1];
        } else {
            return View::fetch();
        }
    }

    /**
     * 修改模型状态
     * @author admin
     * @date 2019-08-08
     */
    public function doStatus()
    {
        try {
            $id = input('post.id');
            $status = input('post.status');
            if (db::name('module')->where('id=' . $id)->update(['status' => $status]) !== false) {
                return ['code' => 0, 'msg' => '操作成功!'];
            } else {
                return ['code' => 1, 'msg' => '操作失败!'];
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 修改模型资料
     * @author admin
     * @date 2019-08-08
     */
    public function edit()
    {
        try {
            if (request()->isPost()) {
                $data = Request::except(['name']);
                if (db::name('module')->update($data) !== false) {
                    return array('code' => 0, 'msg' => '修改成功!');
                } else {
                    return array('code' => 1, 'msg' => '修改失败!');
                }
            } else {
                $map['id'] = input('param.id');
                $info = db::name('module')->field('id,title,name,description,listfields')->where($map)->find();
                $this->assign('info', $info);
                return View::fetch();
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 添加模型，生成模型实体表及字段
     * @author admin
     * @date 2019-08-08
     */
    public function add()
    {
        try {
            if (request()->isPost()) {
                //获取数据库所有表名

                $tables = Db::getConnection()->getTables();

                //组装表名
                $prefix = config('database.connections.mysql.prefix');
                $tablename = $prefix . input('post.name');
                //判断表名是否已经存在
                if (in_array($tablename, $tables)) {
                    return ['code' => 1, 'msg' => '该表已经存在！'];
                }
                $name = ucfirst(input('post.name'));
                $data = Request::except(['emptytable']);
                $data['type'] = 1;
                $moduleid = db::name('module')->insertGetId($data);
                if (empty($moduleid)) {
                    return ['code' => 1, 'msg' => '添加模型失败！'];
                }
                $emptytable = input('post.emptytable');
                if ($emptytable == '0') {
                    Db::execute("CREATE TABLE `" . $tablename . "` (
			  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
			  `catid` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '分类ID',
			  `userid` int(8) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
			  `username` varchar(40) NOT NULL DEFAULT '' COMMENT '用户名',
			  `title` varchar(120) NOT NULL DEFAULT '' COMMENT '标题',
			  `title_style` varchar(225) NOT NULL DEFAULT '' COMMENT '标题样式',
			  `thumb` varchar(225) NOT NULL DEFAULT '' COMMENT '缩略图',
			  `keywords` varchar(120) NOT NULL DEFAULT '' COMMENT '关键词',
			  `description` mediumtext NOT NULL COMMENT '描述',
			  `content` mediumtext NOT NULL  COMMENT '内容',
			  `template` varchar(40) NOT NULL DEFAULT '' COMMENT '模板', 
			  `posid` tinyint(2) unsigned NOT NULL DEFAULT '0' COMMENT '推荐位',
			  `status` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '状态',
			  `recommend` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '允许评论',
			  `readgroup` varchar(100) NOT NULL DEFAULT '' COMMENT '访问权限',
			  `readpoint` smallint(5) NOT NULL DEFAULT '0' COMMENT '阅读权限',
			  `sort` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '排序',
			  `hits` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '点击',
			  `createtime` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
			  `updatetime` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
			  PRIMARY KEY (`id`),
			  KEY `status` (`id`,`status`,`sort`),
			  KEY `catid` (`id`,`catid`,`status`),
			  KEY `sort` (`id`,`catid`,`status`,`sort`)
			) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'catid', '栏目', '', '1', '1', '6', '', '必须选择一个栏目', '', 'catid', '','1','', '1', '1', '1')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'title', '标题', '', '1', '1', '80', '', '标题必须为1-80个字符', '', 'title', 'array (\n  \'thumb\' => \'1\',\n  \'style\' => \'1\',\n  \'size\' => \'55\',\n)','1','',  '2', '1', '1')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'keywords', '关键词', '', '0', '0', '80', '', '', '', 'text', 'array (\n  \'size\' => \'55\',\n  \'default\' => \'\',\n  \'ispassword\' => \'0\',\n  \'fieldtype\' => \'varchar\',\n)','1','',  '3', '1', '1')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'description', 'SEO简介', '', '0', '0', '0', '', '', '', 'textarea', 'array (\n  \'fieldtype\' => \'mediumtext\',\n  \'rows\' => \'4\',\n  \'cols\' => \'55\',\n  \'default\' => \'\',\n)','1','',  '4', '1', '1')");

                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'content', '内容', '', '0', '0', '0', '', '', '', 'editor', 'array (\n  \'edittype\' => \'ueditor\',\n  \'toolbar\' => \'full\',\n  \'default\' => \'\',\n  \'height\' => \'\',\n  \'showpage\' => \'1\',\n  \'enablekeylink\' => \'0\',\n  \'replacenum\' => \'\',\n  \'enablesaveimage\' => \'0\',\n  \'flashupload\' => \'1\',\n  \'alowuploadexts\' => \'\',\n)','1','',  '5', '1', '1')");

                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'createtime', '发布时间', '', '1', '0', '0', 'date', '', 'createtime', 'datetime', '','1','',  '6', '1', '1')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'status', '状态', '', '0', '0', '0', '', '', '', 'radio', 'array (\n  \'options\' => \'发布|1\r\n定时发布|0\',\n  \'fieldtype\' => \'tinyint\',\n  \'numbertype\' => \'1\',\n  \'labelwidth\' => \'75\',\n  \'default\' => \'1\',\n)','1','','7', '1', '1')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'recommend', '允许评论', '', '0', '0', '1', '', '', '', 'radio', 'array (\n  \'options\' => \'允许评论|1\r\n不允许评论|0\',\n  \'fieldtype\' => \'tinyint\',\n  \'numbertype\' => \'1\',\n  \'labelwidth\' => \'\',\n  \'default\' => \'\',\n)','1','', '8', '0', '0')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'readpoint', '阅读收费', '', '0', '0', '5', '', '', '', 'number', 'array (\n  \'size\' => \'5\',\n  \'numbertype\' => \'1\',\n  \'decimaldigits\' => \'0\',\n  \'default\' => \'0\',\n)','1','', '9', '0', '0')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'hits', '点击次数', '', '0', '0', '8', '', '', '', 'number', 'array (\n  \'size\' => \'10\',\n  \'numbertype\' => \'1\',\n  \'decimaldigits\' => \'0\',\n  \'default\' => \'0\',\n)','1','',  '10', '0', '0')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'readgroup', '访问权限', '', '0', '0', '0', '', '', '', 'groupid', 'array (\n  \'inputtype\' => \'checkbox\',\n  \'fieldtype\' => \'tinyint\',\n  \'labelwidth\' => \'85\',\n  \'default\' => \'\',\n)','1','', '11', '0', '1')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'posid', '推荐位', '', '0', '0', '0', '', '', '', 'posid', '','1','', '12', '1', '1')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'template', '模板', '', '0', '0', '0', '', '', '', 'template', '','1','', '13', '1', '1')");

                } else {
                    Db::execute("CREATE TABLE `" . $tablename . "` (
			  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
			  `title` varchar(120) NOT NULL DEFAULT '' COMMENT '标题',
			  `title_style` varchar(225) NOT NULL DEFAULT '' COMMENT '标题样式',
			  `thumb` varchar(225) NOT NULL DEFAULT '' COMMENT '缩略图',
			  `hits` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '点击',
			  `status` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '状态',
			  `userid` int(8) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
			  `username` varchar(40) NOT NULL DEFAULT '' COMMENT '用户名',
			  `sort` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '排序',
			  `createtime` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
			  `updatetime` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
			  `lang` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '语言',
			  `template` varchar(40) NOT NULL DEFAULT '' COMMENT '模板', 
			  PRIMARY KEY (`id`)
			) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'title', '标题', '', '1', '1', '80', '', '标题必须为1-80个字符', '', 'title', 'array (\n  \'thumb\' => \'1\',\n  \'style\' => \'1\',\n  \'size\' => \'55\',\n)','1','',  '2', '1', '1')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'hits', '点击次数', '', '0', '0', '8', '', '', '', 'number', 'array (\n  \'size\' => \'10\',\n  \'numbertype\' => \'1\',\n  \'decimaldigits\' => \'0\',\n  \'default\' => \'0\',\n)','1','',  '8', '0', '0')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'createtime', '发布时间', '', '1', '0', '0', 'date', '', 'createtime', 'datetime', '','1','',  '97', '1', '1')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'template', '模板', '', '0', '0', '0', '', '', '', 'template', '','1','', '99', '1', '1')");
                    Db::execute("INSERT INTO `" . $prefix . "field` (`moduleid`,`field`,`name`,`tips`,`required`,`minlength`,`maxlength`,`pattern`,`errormsg`,`class`,`type`,`setup`,`ispost`,`unpostgroup`,`sort`,`status`,`issystem`) VALUES ( '" . $moduleid . "', 'status', '状态', '', '0', '0', '0', '', '', '', 'radio', 'array (\n  \'options\' => \'发布|1\r\n定时发布|0\',\n  \'fieldtype\' => \'tinyint\',\n  \'numbertype\' => \'1\',\n  \'labelwidth\' => \'75\',\n  \'default\' => \'1\',\n)','1','', '98', '1', '1')");
                }
                if ($moduleid !== false) {
                    return ['code' => 0, 'msg' => '添加模型成功！'];
                }
            } else {
                return View::fetch('edit');
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 删除模型及模型表，模型字段
     * @param $id 主键
     * @return Array
     */
    public function doDelete()
    {
        try {
            $id = input('param.id');
            $module = db::name('module')->find($id);
            if (!$module) {
                return ['code' => 1, 'msg' => '未找到模型记录！'];
            }
            if ($module['issystem'] == 1) return ['code' => 1, 'msg' => '系统模型不可删除！'];

            $tablename = config('database.connections.mysql.prefix') . $module['name'];
            $m = db::name('module')->delete($id); //删除模型
            if ($m) {
                Db::execute("DROP TABLE IF EXISTS `" . $tablename . "`");//删除表
                db::name('Field')->where(array('moduleid' => $id))->delete();//删除模型字段
            }
            return ['code' => 0, 'msg' => '删除成功！'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

}